<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.userName" clearable class="filter-item" style="width: 200px;" placeholder="输入用户名"/>
      <div class="buttonGroup">
        <el-button class="filter_button" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      </div>
    </div>

    <!-- 查询结果 -->
    <MCTable :data-source="dataSource"/>
    <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="sizeChange" />

    <!-- 权限配置对话框 -->
    <el-dialog :visible.sync="permissionDialogFormVisible" title="权限配置">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-position="right" label-width="80px">
        <el-form-item label="账户">
          <p>{{ dataForm.userName }}</p>
        </el-form-item>
        <el-form-item label="电台" prop="radioId">
          <el-select v-model="ruleForm.radioId" placeholder="请选择" @change="selectChange" filterable>
            <el-option
              v-for="item in radioOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item v-show="channelOptions.length>0" label="频率" prop="checkList">
          <div>
            <el-checkbox-group v-model="ruleForm.checkList" class="group">
              <span class="checkbox" v-for="(item, index) in channelOptions" :key="index">
                <el-checkbox :label="item.id" border>{{ item.name }}</el-checkbox>
              </span>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePermission">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import columns from './sysColumns/dataColumn'
import { apiUser } from '../../../api/sys/index'
import { apiCommon } from '../../../api/common'

export default {
  name: 'User',
  components: { Pagination },
  data() {
    return {
      rules: {
        radioId: [
          { required: true, message: '请选择电台', trigger: 'change' }
        ],
        checkList: [
          { required: true, message: '请选择频率', trigger: 'change' }
        ]
      },
      dataSource: {
        headerLines: 1,
        list: [],
        columns: columns,
        operates: {
          fixed: 'right',
          list: [
            { label: '数据权限配置', show: (row) => (true),
              method: (index, row) => {
                this.handlePermission(row)
              }
            }
          ]
        }
      },
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        userName: undefined
      },

      dataForm: {
        userChannels: [],
        userId: undefined,
        userName: undefined
      },
      permissionDialogFormVisible: false,
      permissionForm: {
        roleId: undefined,
        user: '',
        permissions: []
      },
      channelOptions: [],
      radioOptions: [],

      ruleForm: {
        checkList: [],
        radioId: ''
      }

    }
  },
  created() {
    this.getList()
    this.radioInfo()
  },
  methods: {
    selectChange(val) {
      this.ruleForm.checkList = []
      this.channelInfo(val)
    },
    sizeChange(val) {
      this.listQuery.limit = val.limit
      this.getList()
    },
    // radio data
    async radioInfo() {
      const [rerr, radio] = await this.$await(apiCommon.radio())
      if (radio) {
        this.radioOptions = radio.datas.list
      }
    },
    // channel data
    async channelInfo(rid) {
      const [cerr, channel] = await this.$await(apiCommon.channel({ radioId: rid }))
      if (channel) {
        this.channelOptions = channel.datas.list
      }
    },
    async getList() {
      this.$set(this.dataSource, 'options', { loading: true })
      const [err, res] = await this.$await(apiUser.queryUserRadio(this.listQuery))
      if (res) {
        this.dataSource.list = res.datas.list
        this.total = Number(res.datas.total)
      }
      this.$set(this.dataSource, 'options', { loading: false })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        userChannels: [],
        userId: undefined,
        userName: undefined
      }
    },
    // query userRadio
    async userDetail(userId) {
      const [err, res] = await this.$await(apiUser.queryUserRadioDetail({ userId }))
      if (res) {
        this.ruleForm.checkList = res.datas.list.map(item => item.channelId)
        this.ruleForm.radioId = res.datas.list[0]?.radioId ?? ''
        if (this.ruleForm.radioId) {
          this.channelInfo(this.ruleForm.radioId)
        }
      }
    },
    handlePermission(row) {
      this.channelOptions = []
      this.permissionDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields()
      })
      this.dataForm.userName = row.userName
      this.dataForm.userId = row.userId
      this.userDetail(row.userId)
    },
    // add userRadio
    updatePermission() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          const { id, name } = this.radioOptions.filter(item => item.id === this.ruleForm.radioId)[0]
          this.dataForm.userChannels = this.channelOptions
            .filter(item => {
              return this.ruleForm.checkList.includes(item.id) === true
            })
            .map(item => {
              return {
                ...item,
                name: undefined,
                id: undefined,
                radioId: id,
                radioName: name,
                userId: this.dataForm.userId,
                userName: this.dataForm.userName,
                channelId: item.id,
                channelName: item.name
              }
            })
          const [err, res] = await this.$await(apiUser.bindUserRadio({ ...this.dataForm }))
          if (res) {
            this.permissionDialogFormVisible = false
            this.resetForm()
            this.getList()
            this.$notify.success({
              title: '成功',
              message: '关联成功'
            })
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-checkbox-group{
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .checkbox{
    margin-bottom: 10px;
    margin-right: 10px;
  }
}
</style>
